package com.antonauoja.javaril;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import javax.net.ssl.*;
import javax.xml.parsers.*;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

class ConnectionHandler {

    private URL url;
    private HttpsURLConnection httpsConn;
    
    public ConnectionHandler(String url) {
	
	    try {
			this.url = new URL(url);
		    httpsConn = (HttpsURLConnection) this.url.openConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}

    } 
    
    public void post() {
    	System.out.println(httpsConn.getHeaderFields());
    }

    Map getHeader() {
        return httpsConn.getHeaderFields();
    }
    
    public String getContent() {
    	
    	try {
			BufferedReader br = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
	        StringBuilder sb = new StringBuilder(16384);
	        String line;
	        	        
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            br.close();
    		return sb.toString();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "lol fail";
    }
    
    public Status getListStatus() {
    	
        StringBuilder sb = new StringBuilder(16384);
    	
    	try {
			BufferedReader br = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
			
			//Create well formed XML
	        String line;
	        line = br.readLine();
            sb.append(line);
            sb.append('\n');
            sb.append("<status>");
            sb.append('\n');
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            sb.append("</status>");
            System.out.println(sb);

            br.close();
            
            //Parse XML
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db;
			db = dbf.newDocumentBuilder();
		
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(sb.toString()));
            Document doc = db.parse(is);
            
            NodeList nodes = doc.getElementsByTagName("status");
            	
            Element element = (Element) nodes.item(0);
           
           	NodeList status_s = element.getElementsByTagName("user_since");
           	Element row = (Element) status_s.item(0);
           	Date s = new Date(Long.parseLong(getCharacterDataFromElement(row)) * 1000);
           	
           	NodeList status_t = element.getElementsByTagName("count_list");
           	row = (Element) status_t.item(0);
           	int t = Integer.parseInt(getCharacterDataFromElement(row));
           	
           	NodeList status_unread = element.getElementsByTagName("count_unread");
           	row = (Element) status_unread.item(0);
           	int u = Integer.parseInt(getCharacterDataFromElement(row));
           	
        	NodeList status_read = element.getElementsByTagName("count_read");
           	row = (Element) status_read.item(0);
           	int r = Integer.parseInt(getCharacterDataFromElement(row));
           	
           	
           	return new Status(s, t, u, r);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }
    
    public RilList getList() {
    	
        StringBuilder sb = new StringBuilder(16384);
    	
    	try {
			BufferedReader br = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
			
			//Create well formed XML
	        String line;
	        line = br.readLine();
            sb.append(line);
            sb.append('\n');
            sb.append("<read_it_later_list>");
            sb.append('\n');
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            sb.append("</read_it_later_list>");
            
            System.out.println(sb);
            
            br.close();
            
            //Parse XML
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db;
			db = dbf.newDocumentBuilder();
		
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(sb.toString()));
            Document doc = db.parse(is);
			
            NodeList nodes = doc.getElementsByTagName("item");

            RilList rilList = new RilList();

            for (int i = 0; i < nodes.getLength(); i++) {
            	
            	Element element = (Element) nodes.item(i);
            	
            	NodeList item_itemID = element.getElementsByTagName("item_id");
            	Element row = (Element) item_itemID.item(0);
            	int id = Integer.parseInt(getCharacterDataFromElement(row));
            		
            	NodeList item_title = element.getElementsByTagName("title");
            	row = (Element) item_title.item(0);
            	String title = getCharacterDataFromElement(row);
            	
            	NodeList item_url = element.getElementsByTagName("url");
            	row = (Element) item_url.item(0);
            	String url = getCharacterDataFromElement(row);
               
            	NodeList item_time_updated = element.getElementsByTagName("time_updated");
            	row = (Element) item_time_updated.item(0);
            	Date time_updated = new Date(Long.parseLong(getCharacterDataFromElement(row)) * 1000);
            	
            	NodeList item_time_added = element.getElementsByTagName("time_added");
            	row = (Element) item_time_added.item(0);
            	Date time_added = new Date(Long.parseLong(getCharacterDataFromElement(row)) * 1000);
               
            	NodeList state_item = element.getElementsByTagName("state");
            	row = (Element) state_item.item(0);
            	int stateInt = Integer.parseInt(getCharacterDataFromElement(row));
            	boolean state = (stateInt == 0) ? true : false;
            	
            	RilItem newItem = new RilItem(id, title, url, time_updated, time_added, state);
            	rilList.add(newItem);
            }
            
            Element row = (Element) doc.getElementsByTagName("since").item(0);
            Date since = new Date(Long.parseLong(getCharacterDataFromElement(row)) * 1000);
            
            rilList.setDate(since);
            
    		return rilList;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }
	
    public static String getCharacterDataFromElement(Element e) {
        Node child = e.getFirstChild();
        if (child instanceof CharacterData) {
           CharacterData cd = (CharacterData) child;
           return cd.getData();
        }
        return "";
      }

}
